#include "xdb_thread.h"

namespace xdragonball
{
ThreadPool::ThreadPool() {}
ThreadPool::~ThreadPool() {}

int ThreadPool::createEvent(IEvent *ev)
{
	int back = ev->status();
	ev->setStatus(ThreadPool::IEvent::RUN);
	if (_msgq.push(ev) != 0) {
		ev->setStatus(back);
		return -1;
	}
	return 0;
}

static void * static_callback(void *arg)
{
	ThreadPool *pool = (ThreadPool *)(arg);
	pool->dispatch();
}

void ThreadPool::dispatch()
{
	while (true) {
		IEvent *ev;
		_msgq.pop(&ev);
		ev->cb();
		ev->setStatus(ThreadPool::IEvent::DONE);
	}
}

int ThreadPool::run(int num)
{
	if (_vec.size() > 0) {
		return -1;
	}
	for (int i=0; i<num; ++i) {
		pthread_t pid;
		int ret = pthread_create(&pid, NULL, static_callback, this);
		if (ret == 0) {
			_vec.push_back(pid);
		}
	}
	return _vec.size();
}

int ThreadPool::join()
{
	for (int i=0; i<(int)_vec.size(); ++i) {
		pthread_join(_vec[i], NULL);
	}
	_vec.clear();
	return 0;
}

};
